<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.servergroup_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #alert-form="{}">
        <el-alert type="info" show-icon :closable="false">
          <template #title>
            <el-text size="small">配置服务端连接信息，用来接收平台转发的订阅消息至自建服务。</el-text>
          </template>
        </el-alert>
      </template>
      <template #groupId-form="{ }">
        <el-input v-model="this.form.groupId" placeholder="请输入 消费组ID">
          <template #append>
            <el-button-group>
              <el-button @click="generateGroupId">生成</el-button>
            </el-button-group>
          </template>
        </el-input>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/iot/server/serverGroup";
import {mapGetters} from "vuex";
import func from "@/utils/func";
import {getPageList} from "@/api/iot/category";

export default {
  data() {
    const validateId = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9]{16,32}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('长度应在16到32字符之间，允许包含英文字母、数字'));
        return;
      }
      callback();
    };
    const validateHost = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9\/:_\-.@]{1,100}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('长度不超过100字符，允许包含英文字母、数字、斜杠(/)、冒号(:)、下划线(_)、横杠(-)、点(.)和@符号'));
        return;
      }
      callback();
    };
    const validateUsername = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9&;#*\/:_\-.@]{1,64}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('长度应在1到64字符之间，允许包含英文字母数字和常用特殊符号'));
        return;
      }
      callback();
    };
    const validatePassword = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9]{1,128}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('长度应在1到128字符之间，允许包含英文和数字'));
        return;
      }
      callback();
    };
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogWidth: 500,
        labelWidth: 100,
        searchLabelWidth: 100,
        addBtnText: '创建消费组',
        column: [
          {
            label: "消费组名称",
            prop: "groupName",
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入消费名称",
              trigger: "blur"
            }]
          },
          {
            label: "消费组ID",
            prop: "groupId",
            search: true,
            span: 24,
            rules: [{
              required: true,
              trigger: "blur",
              validator: validateId
            }]
          },
          {
            label: "连接类型",
            prop: "linkType",
            type: "radio",
            dicUrl: "/blade-system/dict/dictionary?code=link_type",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            value: 1,
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入订阅类型",
              trigger: "blur"
            }
            ]
          },
          {
            label: "",
            labelWidth: 10,
            prop: 'alert',
            slot: true,
            hide: true,
            span: 24,
          },
          {
            label: "客户端ID",
            prop: "clientId",
            width: 100,
            span: 24,
            display: true,
            hide: true
          },
          {
            label: "地址",
            prop: "host",
            width: 150,
            span: 24,
            hide: true,
            rules: [{
              required: true,
              trigger: "blur",
              validator: validateHost
            }]
          },
          {
            label: "端口",
            prop: "port",
            type: "number",
            width: 100,
            min: 0,
            max: 65535,
            span: 24,
            hide: true,
            rules: [{
              required: true,
              message: "请输入端口",
              trigger: "blur"
            }]
          },
          {
            label: "用户名",
            prop: "username",
            span: 24,
            hide: true,
            rules: [{
              required: true,
              trigger: "blur",
              validator: validateUsername
            }]
          },
          {
            label: "密码",
            prop: "password",
            span: 24,
            hide: true,
            rules: [{
              required: true,
              trigger: "blur",
              validator: validatePassword
            }]
          },
        ],

      },
      data: []
    };
  },
  watch: {
    'form.linkType'() {
      const linkType = this.form.linkType;
      this.$refs.crud.option.column.filter(item => {
        if (item.prop === 'clientId') {
          item.label = linkType === 1 ? "客户端ID" : "交换机名";
        }
      });
    },
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.server_group_add, false),
        viewBtn: this.validData(this.permission.server_group_view, false),
        delBtn: this.validData(this.permission.server_group_delete, false),
        editBtn: this.validData(this.permission.server_group_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    generateGroupId() {
      this.form.groupId = func.strGenerate(26);
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
